import React, { useState, useEffect, useCallback } from "react";
import { NavBar, Image, Grid, Button, Divider, Swiper, Popup, Footer, Toast } from "antd-mobile";
import {
    RightOutline,
    UndoOutline,
    AppstoreOutline,
    HistogramOutline,
    ContentOutline,
    UserOutline,
} from "antd-mobile-icons";

import { useNavigate, useSearchParams } from "react-router-dom";
// import styles from './demo1.less'
import "./My/APP.scss";
import { GridItem } from "antd-mobile/es/components/grid/grid";
import request, { baseUrl } from ".././utils/request";
import { connect } from "react-redux";

const data = [
    {
        id: 1,
        book: "欢迎来到实力至上主义教室",
        author: "天蚕土豆",
        booktype: "奇幻玄幻",
        word: 44.1, //字
        word1: "完结",
        hot: 9999,
        hot1: 9999, //推荐
        directory: "第一章，全球灾变后六十年，小冰冻期结束，各生活大区政府开始大规模收拢待规划无政府区的土地，", //目录
        pic: "https://w.linovelib.com/files/article/image/0/8/8s.jpg",
        brief: "全球灾变后六十年，小冰冻期结束，各生活大区政府开始大规模收拢待规划无政府区的土地，重整资源，全面进入了复苏阶段，而这二十年也被称为“黄金二十年”。\r\n天地为炉，万物为铜，阴阳为炭，造化为工。 气运之争，蟒雀吞龙。 究竟是蟒雀为尊，还是圣龙崛起，凌驾众生？ 这是气掌乾坤的世界，磅礴宏伟，一气可搬山，可倒海，可翻天，可掌阴阳乾坤。 世间源气分九品，三品称玄，六品成天，九品号圣。 吾有一口玄黄气，可吞天地日月星。",
    },
];
var b = Math.floor(Math.random() * 7 + 1);

function Detail(props) {
    const [state, setState] = useState(b);
    const [ss, sss] = useState(data);

    const [params] = useSearchParams();

    const id = params.get("id");

    const [novel, setNovel] = useState([]);

    const [visible1, setVisible1] = useState(false);
    const [visible2, setVisible2] = useState(false);

    const getData1 = async () => {
        const { data } = await request.get("/books/list", { params: { limit: 70 } });

        const data1 = data.data[0].filter((item) => {
            if (item.id == id) {
                return item;
            }
        });

        sss(data1);
        //
    };
    useEffect(() => {
        getData1();
    }, [id]);

    const getData = async () => {
        const { data } = await request.get("/books/list", { params: { page: state, limit: 7 } });

        setNovel(data.data[0]);
    };
    useEffect(() => {
        getData();
    }, [state]);

    const Navigat = useNavigate();

    const hh = (id) => {
        Navigat(`/detail?id=${id}`);
        sss(
            novel.filter((item) => {
                if (item.id === id) {
                    return item;
                }
                window.scrollTo(0, 0);
                location.reload();
            })
        );
    };

    const user = !!props.user[0];

    const j = useCallback(() => {
        Navigat(`/home`);
    });

    const j1 = useCallback(() => {
        Navigat(`/rank`);
    });

    const j3 = useCallback(() => {
        Navigat(`/my`);
    });

    const j2 = useCallback(() => {
        if (user) {
            Navigat(`/bookbox`);
        } else {
            Navigat(`/my`);
        }
    });

    const bookadd = (id) => {
        let books = props.user[0].books;
        books = books.split(",");
        books = books.map((item) => {
            return item * 1;
        });
    
        let userid = props.user[0].user_id;
        let check = books.indexOf(id * 1);
        if (check != -1) {
            Toast.show({
                content: "该书已存在",
                afterClose: () => {
                    console.log("after");
                },
            });
        } else {
            let newbook = "";
            books.push(id * 1);
            books.forEach((item) => {
                newbook += item + "" + ",";
            });
            newbook = newbook.substr(0, newbook.length - 1);
            const { data } = request.put("/books/addbooklist/" + userid, { newbook });
            Toast.show({
                content: "添加成功",
                afterClose: () => {
                    console.log("after");
                },
            });
            props.user[0].books = newbook;
            localStorage.setItem("userInfo", JSON.stringify(props.user[0]));
        }
    };

    return (
        <div
            style={{
                paddingTop: "45px",
                zIndex: "-1",
            }}
        >
            <NavBar
                onBack={() => {
                    window.history.back(-1);
                }}
                style={{ color: "red" }}
                className="Navigation"
            >
                {ss[0].book}{" "}
            </NavBar>
            <Grid columns={3} gap={8}>
                <Grid.Item>
                    <div className={"grid-demo-item-block"}>
                        <Image height="130px" src={ss[0].pic} />
                    </div>
                </Grid.Item>
                <Grid.Item span={2}>
                    {ss.map((item) => {
                        return (
                            <div className="div" key={item.id}>
                                <h2>{item.book}</h2>
                                <div>
                                    <span>{item.author}</span> "著"
                                </div>
                                <p>
                                    {item.hot} 人收藏 / {4564} 人推荐
                                </p>
                                <p className="p">
                                    {77.7} 万字 | {"完结"}
                                </p>
                                <p className="p1">{item.booktype}</p>
                            </div>
                        );
                    })}
                </Grid.Item>
            </Grid>
            <Grid columns={3} gap={8} className="Grid">
                <Grid.Item>
                    <Button className="Button1">开始阅读</Button>
                </Grid.Item>
                <Grid.Item>
                    <Button className="Button" onClick={bookadd.bind(null, id)}>
                        加入书架
                    </Button>
                </Grid.Item>
                <Grid.Item>
                    <Button className="Button">分享本书</Button>
                </Grid.Item>
            </Grid>
            <Divider />
            <Grid columns={4} gap={8} className="JumpKnob">
                <Grid.Item onClick={j}>
                    <AppstoreOutline fontSize={22} />
                    <div>首页</div>
                </Grid.Item>
                <Grid.Item onClick={j1}>
                    <HistogramOutline fontSize={22} />
                    <div>排行榜</div>
                </Grid.Item>
                <Grid.Item onClick={j2}>
                    <ContentOutline fontSize={22} />
                    <div>书架</div>
                </Grid.Item>
                <Grid.Item onClick={j3}>
                    <UserOutline fontSize={22} />
                    <div>我的</div>
                </Grid.Item>
            </Grid>
            <Divider />
            <div className="bbox" style={{ whiteSpace: "pre-wrap" }}>
                {" "}
                {ss[0].brief}
            </div>
            <Divider />
            <Grid columns={3} gap={8} className="div1">
                <Grid.Item>
                    <h2> 章节</h2>
                </Grid.Item>
                <Grid.Item>
                    <div className="spanBox">
                        <span>
                            <Button
                                onClick={() => {
                                    setVisible1(true);
                                }}
                                size={"mini"}
                                style={{ color: "#11d5ff" }}
                                fill="none"
                            >
                                {ss[0].brief}
                            </Button>
                            <Popup
                                visible={visible1}
                                onMaskClick={() => {
                                    setVisible1(false);
                                }}
                                bodyStyle={{ minHeight: "40vh" }}
                            >
                                {data.map((item) => {
                                    return (
                                        <div className="chapter" key={item.id}>
                                            {"第一章"}
                                            <span>
                                                <RightOutline />
                                            </span>
                                        </div>
                                    );
                                })}
                            </Popup>
                        </span>
                    </div>
                </Grid.Item>
                <Grid.Item>
                    <div className="iconRight">
                        <RightOutline />
                    </div>
                </Grid.Item>
            </Grid>
            <Divider />
            <Grid columns={2} gap={8} className="boxxx">
                <Grid.Item>
                    <h2>相关推荐</h2>
                </Grid.Item>
                <Grid.Item></Grid.Item>
            </Grid>
            <Grid columns={1} className="boxx">
                <Grid.Item>
                    <div>
                        <Swiper slideSize={30} trackOffset={5} defaultIndex={0} indicator={() => null}>
                            {novel.map((item, inx) => {
                                return (
                                    <Swiper.Item key={inx} onClick={hh.bind(null, item.id)}>
                                        <div style={{ paddingLeft: "5px" }}>
                                            <Image src={item.pic} />
                                        </div>
                                        <p className="p">{item.book}</p>
                                    </Swiper.Item>
                                );
                            })}
                        </Swiper>
                    </div>
                </Grid.Item>
            </Grid>
            <Divider />
            <Footer label="没有更多了" content="Copyright © 2022 趣学藏书阁"></Footer>
        </div>
    );
}

const mapStateToProps = function (state) {
    console.log("state.userInfo", state.userInfo);
    return {
        user: state.userInfo,
    };
};

const mapDispatchToProps = function (dispatch) {
    return {
        logout() {
            dispatch({ type: "logout" });
        },
    };
};

Detail = connect(mapStateToProps, mapDispatchToProps)(Detail);

export default Detail;
